package com.itheima.cs.utils;

import android.Manifest;
import android.app.Application;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.yingmei.printsdk.JolimarkPrint;
import com.yingmei.printsdk.bean.DeviceInfo;
import com.yingmei.printsdk.bean.SearchCallback;
import com.yingmei.printsdk.bean.TransType;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "MyApplication";
    private static MyApplication instance;
    private final Set<String> deviceMacSet = new HashSet<>();
    private final ArrayList<DeviceInfo> discoveredPrinters = new ArrayList<>();
    private boolean isSearching = false;
    private Activity currentActivity;
    private SearchCallback globalSearchCallback;
    private boolean permissionsGranted = false;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        registerActivityLifecycleCallbacks(this);
        checkPermissions();
    }

    public static MyApplication getInstance() {
        return instance;
    }


    public void startGlobalSearch() {
        if (!permissionsGranted) {
            checkPermissions();
            return;
        }

        if (isSearching) return;
        isSearching = true;

        globalSearchCallback = new SearchCallback() {
            @Override
            public void startDevices() {
                Log.d(TAG, "全局打印机搜索启动");
            }

            @Override
            public void stopDevices(List<DeviceInfo> devices) {
                scheduleNextSearch();
            }

            @Override
            public void findDevices(DeviceInfo deviceInfo) {
                addPrinter(deviceInfo);
            }
        };

        startSearchCycle();
    }

    private void startSearchCycle() {
        JolimarkPrint.searchDevices(this, 5000, TransType.TRANS_ALL, globalSearchCallback);
    }

    private void scheduleNextSearch() {
        if (isSearching) {
            new Handler().postDelayed(this::startSearchCycle, 10000);
        }
    }

    public boolean isSearching() {
        return isSearching;
    }

    public void setSearching(boolean searching) {
        isSearching = searching;
    }


    private void checkPermissions() {
        boolean location = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        boolean wifi = ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_WIFI_STATE) == PackageManager.PERMISSION_GRANTED;

        permissionsGranted = location && wifi;

        if (!permissionsGranted && currentActivity != null) {
            requestPermissions(currentActivity);
        }
    }

    public void requestPermissions(Activity activity) {
        List<String> needed = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            needed.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_WIFI_STATE) != PackageManager.PERMISSION_GRANTED) {
            needed.add(Manifest.permission.ACCESS_WIFI_STATE);
        }

        if (!needed.isEmpty()) {
            ActivityCompat.requestPermissions(activity,
                    needed.toArray(new String[0]),
                    1001);
        }
    }

    public void onPermissionsResult(boolean granted) {
        permissionsGranted = granted;
        if (granted) {
            startGlobalSearch();
        }
    }


    private synchronized void addPrinter(DeviceInfo device) {
        String uniqueId = device.getDid();
        if (!deviceMacSet.contains(uniqueId)) {
            deviceMacSet.add(uniqueId);
            discoveredPrinters.add(device);
            Log.d(TAG, "新增打印机: " + device.getDid());
        }
    }

    public synchronized List<DeviceInfo> getPrinters() {
        return new ArrayList<>(discoveredPrinters);
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {

    }


    @Override
    public void onActivityResumed(Activity activity) {
        currentActivity = activity;
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {

    }


}

